package com.yc.thread;

/**
 * 强制停止线程
 * 两个思路：1. 用stop 2. 抛异常
 * 都不建议使用
 */
public class StopThread {
	
	/**
	 * 使用Thread的stop方法强制停止
	 */
	public void testStop() {
		Thread t1 = new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				System.out.println(i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		t1.start();
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		t1.stop();
		
	}
	
	/**
	 * 使用抛异常的方式停止线程
	 */
	public void testExceptionToStop() {
		Thread t1 = new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				System.out.println(i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (i > 2) {
					int c = 2/0;
				}
			}
		});
		t1.start();
		
	}

	public static void main(String[] args) {
		StopThread st = new StopThread();
//		st.testStop();
		st.testExceptionToStop();

	}

}
